/**
 * @file log.h
 * @author rj.wang (rj.wang@aotbot.com)
 * @brief glog相关日志接口和地址常量等
 * @version 0.1
 * @date 2024-10-28
 * @copyright Copyright (c) 2024
 */

#ifndef __GLOG_FUNC_LOG_H__
#define __GLOG_FUNC_LOG_H__

#include <glog/logging.h>
#include <string>
#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <cstdlib>

namespace common {
namespace log {

/**
 * @brief 路径path_dir是否存在
 */
inline bool IsDirectoryValid(const std::string &path_dir) {
    return access(path_dir.c_str(), F_OK) == 0;
}

/**
 * @brief 根据path_dir创建路径
 */
inline void CreateFolders(const std::string& path_dir) {
  if (!IsDirectoryValid(path_dir)) {
    std::string cmd = "mkdir -p " + path_dir;
    int status = system(cmd.c_str());
    if (status == 0) {
      std::cout << "dir created !!!" << std::endl;
    } else {
      std::cout << "failed to create !!!" << std::endl;
    }
  } else {
    std::cout << "dir exists !!!" << std::endl;
  }
}

/**
 * @brief 获取当前时间（年月日时分秒）的字符串
 */
inline std::string CurTimeString() {
  time_t t;
  time(&t);
  struct tm* tm_obj;
  tm_obj = localtime(&t);
  std::string time_string = std::to_string(tm_obj->tm_year + 1900) + "_" +
                            std::to_string(tm_obj->tm_mon + 1) + "_" +
                            std::to_string(tm_obj->tm_mday) + "_" +
                            std::to_string(tm_obj->tm_hour) + "_" +
                            std::to_string(tm_obj->tm_min) + "_" +
                            std::to_string(tm_obj->tm_sec);
  return time_string;
}

/**
 * @brief glog初始化
 */
inline void InitLog(const std::string& name, const std::string& path_dir) {
  CreateFolders(path_dir);
  google::InitGoogleLogging(name.c_str());
  FLAGS_log_dir = path_dir.c_str();
  FLAGS_alsologtostderr = true;   // 设置日志消息除了日志文件之外是否去标准输出
  FLAGS_colorlogtostderr = true;  // 设置记录到标准输出的颜色消息（如果终端支持）
  FLAGS_logbufsecs = 0;           // 设置可以缓冲日志的最大秒数，0指实时输出
  FLAGS_max_log_size = 10;        // 设置最大日志文件大小（以MB为单位）
  FLAGS_stop_logging_if_full_disk = true;  // 设置是否在磁盘已满时避免日志记录到磁盘
  LOG(INFO) << "glog inited";
}

/**
 * @brief 关闭glog
 */
inline void ShutdownLog() {
  LOG(INFO) << "to shutdown glog";
  google::ShutdownGoogleLogging();
}

/* 日志地址字符串 需要跟auto_clean_config.yaml中的相关路径保持一致 */
const std::string kGlobalPathPlannerLogPath = "/home/aoting/user_config/glogs/global_path_planner";
const std::string kCleanMaskManageLogPath = "/home/aoting/user_config/glogs/clean_mask_manager";
const std::string kDynamicControllerLogPath = "/home/aoting/user_config/glogs/dynamic_controller";

}  // namespace log
}  // namespace common
#endif // __GLOG_FUNC_LOG_H__